#include "WProgram.h"
#include "HITgame.h"

void HITgame::begin(boolean setIndoor,boolean setOutputSerial, boolean setOutputDisplay, boolean setDebug) {
  indoor = setIndoor;
  outputSerial = setOutputSerial;
  outputDisplay = setOutputDisplay;
  debug = setDebug;

  initializePins();

  if(outputSerial){
    Serial.begin(9600);
  }

  sound.begin(PinConfiguration::buzzer);
  tagger.begin(PinConfiguration::irLed,PinConfiguration::irLed,PinConfiguration::muzzleLed,sound);
  //right now a player can only have a tagger so we set it on the initialization
  player.begin(sound,tagger);
}


void HITgame::refresh(){
  triggerValue = digitalRead(PinConfiguration::buttonTrigger); 
  reloadValue = digitalRead(PinConfiguration::buttonReload);
  modeValue = digitalRead(PinConfiguration::buttonMode);

  player.refreshStatus();
  tagger.refreshStatus();
  sound.refreshStatus();

  //for every loop there are two main groups of functions
  //the ones to execute if the player is alive
  //and the ones to execute if the player is dead
  if(player.isAlive){
    //once a loop check if the trigger button is pressed
    if (triggerValue){
      if(debug){ 
        Serial.println("-trigger press-"); 
      } //TODO transform this in some kind of display library
      //if it is check if the player is able to shoot
      if(player.wakeUpMoment > 0 && !player.reloadMoment == 0){
        //if it is shoot
        tagger.startShoot(player.team,player.number);
      }
    }

    if(reloadValue){
      if(debug){ 
        Serial.println("-reload press-"); 
      }
      player.startReload();
    }

    if(modeValue){
      //right now we do not have a use for the mode button in the IR shield
      if(debug){ 
        Serial.println("-mode press-"); 
      }
    }
  }
  else {
    //in case some special functions for dead players
    //are needed those functions should be there
  }
}

//this function just encapsualtes the hit interrupt
//I have found no way to call tagger.receive directly
void HITgame::interrupt(){
  tagger.receive();
}

void HITgame::initializePins(){
  //we begin by setting everything to low to avoid
  //burning any components in case of a hang beyond
  //pinMode(PinConfiguration::irPower,OUTPUT);
  //digitalWrite(PinConfiguration::irPower,LOW);
  pinMode(PinConfiguration::muzzleLed,OUTPUT);
  digitalWrite(PinConfiguration::muzzleLed,LOW);
  pinMode(PinConfiguration::irCheck,OUTPUT);
  digitalWrite(PinConfiguration::irCheck,LOW);
  pinMode(PinConfiguration::irLed, OUTPUT);
  digitalWrite(PinConfiguration::irLed,LOW);
  pinMode(PinConfiguration::buttonTrigger,INPUT);
  pinMode(PinConfiguration::buttonReload,INPUT);
  pinMode(PinConfiguration::buttonMode,INPUT);
  pinMode(PinConfiguration::irReceiver,INPUT);
  pinMode(PinConfiguration::buzzer,OUTPUT);


  //set the power of the IR to high 
  if(indoor){
    //digitalWrite(PinConfiguration::irPower,LOW);
  }
  else {
    //digitalWrite(PinConfiguration::irPower,HIGH);
  }

}

